#import "FlutterDouyinPlugin.h"
#import<DouyinOpenSDK/DouyinOpenSDKApplicationDelegate.h>
#import <DouyinOpenSDK/DouyinOpenSDKAuth.h>
#import <DouyinOpenSDK/DouyinOpenSDKShare.h>


static FlutterMethodChannel *channel;

@implementation FlutterDouyinPlugin

+ (void)registerWithRegistrar:(NSObject <FlutterPluginRegistrar> *)registrar {

    //    NSObject<FlutterTaskQueue>* taskQueue =
    //        [[registrar messenger] makeBackgroundTaskQueue];

    channel = [FlutterMethodChannel
            methodChannelWithName:@"flutter_douyin"
                  binaryMessenger:[registrar messenger]];


    FlutterDouyinPlugin *instance = [[FlutterDouyinPlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    if ([@"getPlatformVersion" isEqualToString:call.method]) {
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    }
    if ([@"setPlatformKey" isEqualToString:call.method]) {//设置抖音平台key
        NSDictionary *arguments = call.arguments;
        NSString *_key = [arguments objectForKey:@"iosKey"];
        [[DouyinOpenSDKApplicationDelegate sharedInstance] registerAppId:_key];
        result(@"success");
    } else if ([@"douyinOpenSDKShareRequest" isEqualToString:call.method]) {
        DouyinOpenSDKShareRequest *req = [[DouyinOpenSDKShareRequest alloc] init];


        NSDictionary *args = [call arguments];
        NSString *shareType = args[@"shareType"];

        if (args[@"state"] != nil) {
            req.state = args[@"state"];
        } else {
            result(@"缺少参数");
            return;
        }

        if ([shareType isEqualToString:@"Capture"]) {//打开视频
            req.shareAction = DouyinOpenSDKShareTypeCapture;
        } else if ([shareType isEqualToString:@"mediaType"]) {
            NSString *mediaType = args[@"mediaType"];

            NSArray *media = args[@"media"];
            req.localIdentifiers = media; // NSArray
            if ([mediaType isEqualToString:@"Image"]) {
                req.mediaType = DouyinOpenSDKShareMediaTypeImage;
            } else if ([mediaType isEqualToString:@"Video"]) {
                req.mediaType = DouyinOpenSDKShareMediaTypeVideo;
            }
            NSString *landedPageType = args[@"landedPageType"];
            if ([landedPageType isEqualToString:@"Clip"]) {
                req.landedPageType = DouyinOpenSDKLandedPageClip; // 剪辑页面
            } else if ([landedPageType isEqualToString:@"Edit"]) {
                req.landedPageType = DouyinOpenSDKLandedPageEdit; // 编辑页面
            } else if ([landedPageType isEqualToString:@"Publish"]) {
                req.landedPageType = DouyinOpenSDKLandedPagePublish; // 发布页面，现只支持单视频（需要抖音14.7版本以上）
            }


        }


        if (args[@"hashtag"] != nil) {
            req.hashtag = args[@"hashtag"];
        }


        [req sendShareRequestWithCompleteBlock:^(DouyinOpenSDKShareResponse *_Nonnull respond) {
            NSMutableDictionary *dyAuthDic = [[NSMutableDictionary alloc] init];
            if (respond.isSucceed) {
                [dyAuthDic setValue:@"200" forKey:@"code"];
                [dyAuthDic setValue:@"分享成功" forKey:@"msg"];
                NSLog(@"分享成功返回：%@", dyAuthDic);
                [channel invokeMethod:@"ISO_DouyinOpenSDKShareRequest" arguments:dyAuthDic];
            } else {
                [dyAuthDic setValue:@(respond.errCode) forKey:@"code"];
                [dyAuthDic setValue:respond.errString forKey:@"errString"];
                NSLog(@"分享失败返回：%@", dyAuthDic);
                [channel invokeMethod:@"ISO_DouyinOpenSDKShareRequest" arguments:dyAuthDic];
            }

        }];
        result(@"success");

    } else if ([@"douyinOpenSDKAuthRequest" isEqualToString:call.method]) {

        NSDictionary *dictionary = call.arguments;
        NSArray *permission = dictionary[@"permissionMest"];
        NSArray *permissionOptional = dictionary[@"permissionOptional"];

        NSMutableString *permissionmest = [[NSMutableString alloc] init];
        for (int i = 0; i < permission.count; i++) {
            NSString *_p = [permission[i] stringByAppendingString:@","];
            [permissionmest insertString:i + 1 == permission.count ? permission[i]
                                                                   : _p atIndex:permissionmest.length];
        }

        NSLog(@"resp:%@", permission);


        DouyinOpenSDKAuthRequest *dyrequest = [[DouyinOpenSDKAuthRequest alloc] init];
        dyrequest.permissions = [NSOrderedSet orderedSetWithObject:permissionmest];
        if (permissionOptional != nil) {
            NSLog(@"Optional:%@", permissionOptional);
            for (int i = 0; i < permissionOptional.count; i++) {
                NSString *permissionName = permissionOptional[i];
                dyrequest.additionalPermissions = [NSOrderedSet orderedSetWithObjects:
                        @{@"permission": permissionName, @"defaultChecked": @"1"},
                        nil];
            }

        }

        __weak typeof(self) ws = self;
        [dyrequest sendAuthRequestViewController:self completeBlock:^(
                DouyinOpenSDKAuthResponse *_Nonnull resp) {
            __strong typeof(ws) sf = ws;
            NSMutableDictionary *dyAuthDic = [[NSMutableDictionary alloc] init];
            if (resp.errCode == 0) {
                NSOrderedSet *orderSet = resp.grantedPermissions;
                NSArray *permissinosArray = [orderSet array];
                NSMutableString *grantedPermissions = [[NSMutableString alloc] init];
                for (int i = 0; i < permissinosArray.count; i++) {
                    NSString *index = permissinosArray[i];
                    NSString *_allpermission = [index stringByAppendingString:@","];
                    [grantedPermissions insertString:i + 1 == permissinosArray.count ? index
                                                                                     : _allpermission atIndex:grantedPermissions.length];
                }
                [dyAuthDic setValue:resp.code forKey:@"code"];
                [dyAuthDic setValue:grantedPermissions forKey:@"permissions"];
                NSLog(@"授权成功返回：%@", dyAuthDic);
                [channel invokeMethod:@"ISO_DouyinOpenSDKAuthRequest" arguments:dyAuthDic];
            } else {
                [dyAuthDic setValue:resp.code forKey:@"code"];
                [dyAuthDic setValue:resp.errString forKey:@"errString"];
                NSLog(@"授权失败返回：%@", dyAuthDic);
                [channel invokeMethod:@"ISO_DouyinOpenSDKAuthRequest" arguments:dyAuthDic];
            }
        }
        ];
        result(@"success");
    } else if ([@"shareImage" isEqualToString:call.method]) {
        NSDictionary *args = call.arguments;
        NSString *path = args[@"path"];
        UIImage *image = [UIImage imageWithContentsOfFile:path];

        if (!image) {
            result([FlutterError errorWithCode:@"image_error" message:@"图片加载失败" details:nil]);
            return;
        }

        // 请求权限
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized ||
                status == PHAuthorizationStatusLimited) {
                __block NSString *localIdentifier = nil;
                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                    PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
                    localIdentifier = req.placeholderForCreatedAsset.localIdentifier;
                }                                 completionHandler:^(BOOL success,
                                                                      NSError *_Nullable error) {
                    if (success && localIdentifier) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            DouyinOpenSDKShareRequest *req = [[DouyinOpenSDKShareRequest alloc] init];
                            req.localIdentifiers = @[localIdentifier];
                            req.shareAction = DouyinOpenSDKShareTypeShareContentToIM;
                            [req sendShareRequestWithCompleteBlock:^(
                                    DouyinOpenSDKShareResponse *_Nonnull respond) {
                                if (respond.isSucceed) {
                                    result(@"success");
                                } else {
                                    result([FlutterError errorWithCode:@"share_failed"
                                                               message:respond.errString
                                                               details:@(respond.errCode)]);
                                }
                            }];
                        });
                    } else {
                        result([FlutterError errorWithCode:@"save_failed" message:@"保存图片到相册失败" details:error.localizedDescription]);
                    }
                }];
            } else {
                result([FlutterError errorWithCode:@"no_permission" message:@"无相册权限" details:nil]);
            }
        }];

    } else if ([@"isDouYinInstalled" isEqualToString:call.method]) {
        NSURL *url = [NSURL URLWithString:@"snssdk1128://"];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            result(@(YES));
        } else {
            result(@(NO));
        }
    } else {
        result(FlutterMethodNotImplemented);
    }
}

@end
